package mapi.flightrecorder;

import java.io.IOException;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {

	Menu menu;											
	TextView tvLatitude;
	TextView tvLongitude;
	TextView tvAltitude;
	TextView tvSpeed;
	TextView tvGpsStatus;
	TextView tvAccuracy;
	TextView tvSessionID;
	TextView tvUpdates;
	TextView tvBearing;
	TextView tvMinDistance;
	TextView tvMinTime;
	TextView tvStart;
	TextView tvLast;
	TextView tvAvgAccuracy;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		DataBaseHelper databasehelper = new DataBaseHelper(this);

		try {
			databasehelper.createDataBase();
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}
	databasehelper.openDataBase();
	databasehelper.close();
		

		tvLatitude = (TextView) findViewById(R.id.tvLatitude);
		tvLongitude = (TextView) findViewById(R.id.tvLongitude);
		tvAltitude = (TextView) findViewById(R.id.tvAltitude);
		tvSpeed = (TextView) findViewById(R.id.tvSpeed);
		tvGpsStatus = (TextView) findViewById(R.id.tvGpsStatus);
		tvAccuracy = (TextView) findViewById(R.id.tvAccuracy);
		tvSessionID = (TextView) findViewById(R.id.tvSessionID);
		tvUpdates = (TextView) findViewById(R.id.tvUpdates);
		tvBearing = (TextView) findViewById(R.id.tvBearing);
		tvStart = (TextView) findViewById(R.id.tvStart);
		tvAvgAccuracy = (TextView) findViewById(R.id.tvAvgAccuracy);
		tvLast = (TextView) findViewById(R.id.tvLast);

	}// OnCreate

	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			updateUI(intent);
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(broadcastReceiver);
	}// onPause

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}// onDestroy

	@Override
	public void onResume() {
		super.onResume();
		registerReceiver(broadcastReceiver, new IntentFilter(
				BackgroundService.BROADCAST_ACTION));

	}

	@Override
	protected void onStop() {
		super.onStop();
	}// OnStop

	private void updateUI(Intent intent) {
		double latitude = intent.getDoubleExtra("latitude", 0);
		double longitude = intent.getDoubleExtra("longitude", 0);
		double altitude = intent.getDoubleExtra("altitude", 0);
		float speed = intent.getFloatExtra("speed", 0);
		float accuracy = intent.getFloatExtra("accuracy", 0);
		float bearing = intent.getFloatExtra("bearing", 0);
		double sessionid = intent.getDoubleExtra("sessionid", 0);
		String UpdatesCount = intent.getStringExtra("updatescount");
		String Last = intent.getStringExtra("last");
		String AvgAccuracy = intent.getStringExtra("avgaccuracy");
		String Start = intent.getStringExtra("start");
		
		tvLatitude.setText(Double.toString(latitude));
		tvLongitude.setText(Double.toString(longitude));
		tvAltitude.setText(Double.toString(altitude));
		tvAccuracy.setText(Float.toString(accuracy));
		tvSpeed.setText(Float.toString(speed));
		tvBearing.setText(Float.toString(bearing));
		tvSessionID.setText(Double.toString(sessionid));
		tvLast.setText(Last);
		tvUpdates.setText(UpdatesCount);
		tvStart.setText(Start);
		tvAvgAccuracy.setText(AvgAccuracy);
		

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.main_menu, menu);
		this.menu = menu;
		MenuItem miStartStop = menu.findItem(R.id.startstop);

		if (isMyServiceRunning() == true) {
			miStartStop.setTitle("Stop");
			miStartStop.setIcon(R.drawable.stop);

		} else {
			miStartStop.setTitle("Start");
			miStartStop.setIcon(R.drawable.start);
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.preferences:

			Intent settingsActivity = new Intent(getBaseContext(),
					Preferences.class);
			startActivity(settingsActivity);

			return true;

		case R.id.quit:
			finish();
			return true;
		case R.id.startstop:
			StartStopService();
			return true;
		case R.id.export:
			Intent exportActivity = new Intent(getBaseContext(),
					ListSession.class);
			startActivity(exportActivity);
			return true;
		}
		return false;
	}

	private void StartStopService() {

		MenuItem miStartStop = menu.findItem(R.id.startstop);

		if (isMyServiceRunning() == true) {
			stopService(new Intent(Main.this, BackgroundService.class));
			Toast.makeText(getApplicationContext(), "Stopping service",
					Toast.LENGTH_SHORT).show();
			miStartStop.setTitle("Start");
			miStartStop.setIcon(R.drawable.start);

		} else {
			startService(new Intent(Main.this, BackgroundService.class));

			Toast.makeText(getApplicationContext(), "Starting service",
					Toast.LENGTH_SHORT).show();

			miStartStop.setTitle("Stop");
			miStartStop.setIcon(R.drawable.stop);
		}

	}

	private boolean isMyServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if ("mapi.flightrecorder.BackgroundService".equals(service.service
					.getClassName())) {
				return true;
			}
		}
		return false;
	}

}// class MongpsloggerActivity

